package cn.assist.easydao.dao.sqlcreator;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.BigDecimalConverter;
import org.apache.commons.beanutils.converters.DateConverter;
import org.springframework.jdbc.core.RowCallbackHandler;

import cn.assist.easydao.util.Inflector;

/**
 * 查询映射结果集到entity
 * 
 * @author caixb
 *
 * @param <T>
 */
public class SpringResultHandler<T> implements RowCallbackHandler {

	private Class<T> entityClass;
	private List<T> dataList;

	public SpringResultHandler(Class<T> entityClass) {
		this.entityClass = entityClass;
		this.dataList = new ArrayList<>();
	}

	public void processRow(ResultSet rs) throws SQLException {
		T rsEntity = null;
		try {
			rsEntity = entityClass.newInstance();
		} catch (InstantiationException | IllegalAccessException e1) {
			e1.printStackTrace();
		}
		Field[] fields = rsEntity.getClass().getDeclaredFields();
		Inflector inf = Inflector.getInstance();
		try {
			for (Field field : fields) {
				Object columnValue = null;
				try {
					columnValue = rs.getObject(inf.underscore(field.getName())); // 取结果集中的值
				} catch (Exception e) {
					continue;
				}
				ConvertUtils.register(new DateConverter(null), java.util.Date.class);
				BigDecimalConverter bd = new BigDecimalConverter(BigDecimal.ZERO);    
			    ConvertUtils.register(bd, java.math.BigDecimal.class);
				BeanUtils.copyProperty(rsEntity, field.getName(), columnValue); // 指定字段copy值
			}
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		dataList.add(rsEntity);
	}

	public List<T> getDataList() {
		return dataList;
	}

	public void setDataList(List<T> dataList) {
		this.dataList = dataList;
	}

}
